package com.hs.zookeeper.util;

import org.apache.log4j.Logger;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: songhao
 * @Date: 2020/12/29
 * @Description: TODO
 */
public class ZkUtil {

    static Logger logger = Logger.getLogger(ZkUtil.class);

    /**
     * 获取zookeeper连接
     * @param ipAddr 连接地址
     * @return
     */
    public static ZooKeeper getZkClient(String ipAddr){
        ZooKeeper zookeeper = null;
        try{
            //计数器对象
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            //服务器远程地址
            zookeeper = new ZooKeeper(ipAddr, 5000, new Watcher() {
                public void process(WatchedEvent watchedEvent) {
                    if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
                        logger.info("成功获取到zookeeper连接...");
                        countDownLatch.countDown();
                    }
                }
            });
            //主线程阻塞等待连接对象的创建成功
            countDownLatch.await();
            logger.info("成功获取到zookeeper连接,sessionId为===>" + zookeeper.getSessionId());
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return zookeeper;
    }

    /**
     * 关闭zookepper的连接
     * @param zooKeeper
     */
    public static void close(ZooKeeper zooKeeper){
        try{
            if(zooKeeper != null){
                zooKeeper.close();
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
    }


    /**
     * 获取默认的ACL权限列表,为所有权限
     * @return
     */
    public static List<ACL> getDefaultAclList(){
        List<ACL> aclList = new ArrayList<>();
        Id id = new Id();
        id.setId("1");
        id.setScheme("world:anyone");
        ACL acl = new ACL();
        //增删改查和管理权限
        acl.setPerms(ZooDefs.Perms.ALL);
        aclList.add(acl);
        return aclList;
    }
}
